package com.example.administrator.guosai51tianqibiao;

import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TimeUtils;
import android.widget.TextView;

import com.nle.mylibrary.forUse.zigbee.FourChannelValConvert;
import com.nle.mylibrary.forUse.zigbee.Zigbee;
import com.nle.mylibrary.transfer.DataBusFactory;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private TextView tv_temp,tv_hum;
    private Zigbee zigbee;
    private TextToSpeech  textToSpeech =null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        Mythread mythread=new Mythread();
        mythread.start();

    }
    private void  init(){
        textToSpeech=new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if(i==0){
                    Log.i("main",i+"");
                }
            }
        });
        tv_hum=findViewById(R.id.tv_hum);
        tv_temp=findViewById(R.id.tv_temp);
        zigbee=new Zigbee(DataBusFactory.newSocketDataBus("172.18.14.200",4196));
    }
    private class Mythread extends  Thread{
        @Override
        public void run() {
            while (true){
                try {
                    Thread.sleep(2000);
                    double[] fourEnter = zigbee.getFourEnter();
                    double temperature = FourChannelValConvert.getTemperature(fourEnter[0]);
                    double humidity = FourChannelValConvert.getHumidity(fourEnter[1]);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_temp.setText(temperature+"度");
                            tv_hum.setText(humidity+"RH");
                        }
                    });
                    textToSpeech.setLanguage(Locale.CHINESE);
                    //设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                    textToSpeech.setPitch(1f);
                    //设置语速
                    textToSpeech.setSpeechRate(1f);
                    textToSpeech.speak("当前温度是"+ temperature+"度,当前湿度是"+humidity+"RH",TextToSpeech.QUEUE_FLUSH, null);
                    Thread.sleep(8000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                catch (Exception e ) {
                    e.printStackTrace();
                }
            }
        }
    }
}
